import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { 
  Form, 
  FormItem, 
  Input, 
  Button, 
  Card, 
  Message, 
  Space 
} from '@hi-ui/hiui'
import { useUserStore } from '../store/userStore'
import './Login.css'

const Login = () => {
  const navigate = useNavigate()
  const { login, loginLoading, isLoggedIn } = useUserStore()
  const [formData, setFormData] = useState({
    identifier: '',
    password: '',
    loginType: 'pc',
    loginMethod: 'password'
  })

  // 如果已经登录，直接跳转到首页
  useEffect(() => {
    if (isLoggedIn) {
      navigate('/')
    }
  }, [isLoggedIn, navigate])

  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleSubmit = async () => {
    try {
      // 表单验证
      if (!formData.identifier.trim()) {
        Message.error('请输入手机号')
        return
      }
      if (!formData.password.trim()) {
        Message.error('请输入密码')
        return
      }

      await login(formData)
      Message.success('登录成功')
      navigate('/')
    } catch (error) {
      Message.error(error.message || '登录失败')
    }
  }

  return (
    <div className="login-container">
      <div className="login-content">
        <Card className="login-card">
          <div className="login-header">
            <h1>系统登录</h1>
            <p>欢迎使用中后台管理系统</p>
          </div>
          
          <Form className="login-form">
            <FormItem label="手机号" required>
              <Input
                placeholder="请输入手机号"
                value={formData.identifier}
                onChange={(e) => handleInputChange('identifier', e.target.value)}
                size="lg"
              />
            </FormItem>
            
            <FormItem label="密码" required>
              <Input
                type="password"
                placeholder="请输入密码"
                value={formData.password}
                onChange={(e) => handleInputChange('password', e.target.value)}
                size="lg"
              />
            </FormItem>
            
            <FormItem>
              <Button
                type="primary"
                size="lg"
                loading={loginLoading}
                onClick={handleSubmit}
                className="login-button"
              >
                登录
              </Button>
            </FormItem>
          </Form>
          
          <div className="login-footer">
            <Space>
              <span>测试账号：13297939390</span>
              <span>密码：123456</span>
            </Space>
          </div>
        </Card>
      </div>
    </div>
  )
}

export default Login
